#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDir"
#include "QtCore"
#include "QTextStream"
#include "QLabel"
#include <QScreen>
#include <QPainter>
#include <QDesktopServices>
#include "xqat_json.h"
#include <QCryptographicHash>


struct weather_t weather = {};
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    sys_init();
}

MainWindow::~MainWindow(void)
{
    delete ui;
}

void MainWindow::on_pushButton_pressed()
{
    set_weather(ui->lineEdit->text());
}

void MainWindow::on_pushButton_1_pressed(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String("https://github.com/xqyjlj")));
}

void MainWindow::on_pushButton_2_pressed(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String(
                                       "https://www.cnblogs.com/xqyjlj/articles/13184306.html")));
}

void MainWindow::on_pushButton_3_pressed(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String(
                                       "https://www.cnblogs.com/xqyjlj/articles/13184306.html")));
}

void MainWindow::on_pushButton_4_pressed(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String(
                                       "https://www.cnblogs.com/xqyjlj/articles/13184306.html")));
}

void MainWindow::on_pushButton_5_pressed(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String(
                                       "https://www.cnblogs.com/xqyjlj/articles/13184306.html")));
}

void MainWindow::on_pushButton_6_pressed(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String(
                                       "https://www.cnblogs.com/xqyjlj/articles/13184306.html")));
}

void MainWindow::on_pushButton_7_pressed(void)
{
    QDesktopServices::openUrl(QUrl(QLatin1String(
                                       "https://www.cnblogs.com/xqyjlj/articles/13184306.html")));
}

void MainWindow::sys_init(void)
{
    qApp->setPalette(QPalette(QColor(248, 251, 254)));
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    xqat_blog_c.set_Avatar(ui->label_head);
    set_weather("佛山");
    set_ascii_art("XQYJLJ", "isometric1.flf");
    initTranslator();
}

void MainWindow::set_weather(QString city)
{
    QNetworkAccessManager *manage = new QNetworkAccessManager(this);
    QNetworkRequest network_request;
    /*设置发送数据*/
    network_request.setUrl(QUrl("http://wthrcdn.etouch.cn/weather_mini?city=" + city));
    network_request.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0");
    /*发送get网络请求*/
    connect(manage, SIGNAL(finished(QNetworkReply*)), this, SLOT(weather_replyFinished(QNetworkReply*))); //关联信号和槽
    manage->get(network_request);
}

void MainWindow::weather_replyFinished(QNetworkReply *reply)
{
    QString all = reply->readAll();
    reply->deleteLater();
    xqat_weather_c.parse_json_data(&weather, all);
    xqat_weather_c.set_Controls(&weather, ui->tableWidget, ui->label_5);
}

/*当用户拖动文件到窗口部件上时候，就会触发dragEnterEvent事件*/
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    /*如果为文件，则支持拖放*/
    if (event->mimeData()->hasFormat("text/uri-list")) {
        event->acceptProposedAction();
    }
}

/*当用户放下这个文件后，就会触发dropEvent事件*/
void MainWindow::dropEvent(QDropEvent *event)
{
    /*注意：这里如果有多文件存在，意思是用户一下子拖动了多个文件，而不是拖动一个目录
    如果想读取整个目录，则在不同的操作平台下，自己编写函数实现读取整个目录文件名*/
    QList<QUrl> urls = event->mimeData()->urls();
    if(urls.isEmpty()) {
        return;
    }
    /*往文本框中追加文件名*/
    foreach(QUrl url, urls) {
        QString file_name = url.toLocalFile();
        qDebug() << file_name;
        xqat_Figure_bed_c.Add_treeWidget(ui->treeWidget, file_name, 0);
        set_figure_bed(file_name);
//        xqat_Figure_bed_c.Add_treeWidget(ui->treeWidget_2, file_name, 1);
    }
}

void MainWindow::initTranslator(void)
{
    /*加载鼠标右键菜单翻译文件*/
    QTranslator *translator1 = new QTranslator(qApp);
    translator1->load(":/img/img/qt_zh_CN.qm");
    qApp->installTranslator(translator1);
    /*加载富文本框鼠标右键菜单翻译文件*/
    QTranslator *translator2 = new QTranslator(qApp);
    translator2->load(":/img/img/widgets.qm");
    qApp->installTranslator(translator2);
}

void MainWindow::set_figure_bed(QString img)
{
    QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(this);
    connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(figure_bed_replyFinished(QNetworkReply*)));
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpg"));
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                        QVariant("form-data; name=\"smfile\"; filename=\"image.png\""));
    QFile *file = new QFile(img);
    if(!file->open(QIODevice::ReadOnly)) {
        qDebug() << "=================================";
    } else {
        imagePart.setBodyDevice(file);
        multiPart->append(imagePart);
    }
    QNetworkRequest request;
    request.setUrl(QUrl("https://sm.ms/api/v2/upload"));
    networkAccessManager->post(request, multiPart);
}

void MainWindow::figure_bed_replyFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError) {
        QByteArray allData = reply->readAll();
//        qDebug() << QString(allData);
        QJsonParseError json_error;
        QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &json_error));
        if(json_error.error != QJsonParseError::NoError) {
//            qDebug() << "json error!";
            return;
        }
        QJsonObject rootObj = jsonDoc.object();
        if(rootObj.contains("data")) {
            QJsonObject subObj = rootObj.value("data").toObject();
            qDebug() << subObj["url"].toString();
            xqat_Figure_bed_c.Add_treeWidget(ui->treeWidget_2, subObj["url"].toString(), 1);
        }
    } else {
//        qDebug() << "=========";
    }
    reply->deleteLater();
}

void MainWindow::set_ascii_art(QString ascii, QString art)
{
    QNetworkAccessManager *manage = new QNetworkAccessManager(this);
    QNetworkRequest network_request;
    ascii.replace(" ", "%20");
    network_request.setUrl(
        QUrl("http://ascii.mastervb.net/figlet.ajax.php?message=" +
             ascii + "&rtol=undefined&old_layout=undefined&font=" +
             art + "&html_mode=undefined"));
    network_request.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0");
    connect(manage, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(ascii_art_replyFinished(QNetworkReply*)));
    manage->get(network_request);
}

void MainWindow::ascii_art_replyFinished(QNetworkReply *reply)
{
    QString all = reply->readAll();
    int head = all.indexOf("<div id=\"image\">");
    int end = all.indexOf("<div id=\"source\">");
    all = all.mid(head, end - head);
    ui->textEdit->setHtml(all);
    reply->deleteLater();
}

void MainWindow::on_pushButton_11_pressed()
{
    set_ascii_art(ui->lineEdit_3->text(), ui->comboBox_9->currentText());
}
